package com.jeff.practice;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class VirtualThreadExample {
    public static void main(String[] args) {
        // 创建一个虚拟线程执行器
        try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {

            // 提交任务
            for (int i = 0; i < 30; i++) {
                final int taskId = i;
                executor.submit(() -> {
                    System.out.println("Executing task " + taskId + " in thread " + Thread.currentThread().getName());
                    try {
                        // 模拟任务执行
                        Thread.sleep(1000); // 注意：在虚拟线程中，sleep不会阻塞物理线程
                    }
                    catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                });
            }

            // 关闭线程池
            executor.shutdown();
            try {
                // 等待线程池中的任务完成
                if (!executor.awaitTermination(60, java.util.concurrent.TimeUnit.SECONDS)) {
                    executor.shutdownNow(); // 强制关闭
                }
            }
            catch (InterruptedException e) {
                executor.shutdownNow();
            }
        }

        System.out.println("All tasks completed.");
    }
}
